package com.helsinki.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.helsinki.mapper.PermissionMapper;
import com.helsinki.mapper.RoleMapper;
import com.helsinki.mapper.UserMapper;
import com.helsinki.pojo.Permission;
import com.helsinki.pojo.Product;
import com.helsinki.pojo.Role;
import com.helsinki.pojo.UserInfo;
import com.helsinki.service.UserInfoService;
import com.helsinki.utils.QueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Service
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public PageInfo<UserInfo> queryAll(Integer pageNum, Integer pageSize) {
        // 只有在要分页的查询之前才能设置分页信息
        PageHelper.startPage(pageNum, pageSize);
        List<UserInfo> list = userMapper.findAll();
        // PageInfo 封装了所有的分页信息
        return new PageInfo<>(list);
    }

    @Override
    public void update(UserInfo userInfo) {
        userMapper.updateUser(userInfo);
    }

    @Override
    public void updateUserRole(QueryVo queryVo) {

        roleMapper.closeForeignKey();
        String id = queryVo.getUserId();
        List<String> RIds = List.of(queryVo.getRoleIds());
        userMapper.deleteRoleByUId(id);
        for (String rId : RIds) {
            if (!rId.isEmpty()) {
                userMapper.insertRoleByUId(rId, id);
            }
        }
        roleMapper.openForeignKey();

    }

    @Override
    public void deleteById(String id) {
        userMapper.closeForeignKey();
        userMapper.deleteById(id);
        userMapper.deleteRoleByUId(id);
        userMapper.openForeignKey();
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = userMapper.findByUsername(username);

//        if (Objects.isNull(userInfo)) { // 用户不存在
//            throw new AuthenticationException("账号不存在") {
//            };
//        }
        if (userInfo != null) {
            List<Permission> permissions = permissionMapper.findPermissionByUid(userInfo.getId());
            List<GrantedAuthority> grantedAuthorities = new ArrayList <>();
            for (Permission permission : permissions) {
                if (permission != null && permission.getPermissionName()!=null) {
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getPermissionName());
                    //1：此处将权限信息添加到 GrantedAuthority 对象中，在后面进行全权限验证时会使用GrantedAuthority 对象。
                    grantedAuthorities.add(grantedAuthority);
                }
            }
            return new User(userInfo.getUsername(), userInfo.getPassword(), grantedAuthorities);
        } else {
            throw new UsernameNotFoundException("admin: " + username + " do not exist!");
        }

        // 设置固定角色 - 用来做授权
//        List<GrantedAuthority> list = new ArrayList<>();
//        list.add(new SimpleGrantedAuthority("ROLE_USER"));
//        User user = new User(userInfo.getUsername(), userInfo.getPassword(), list);
//        return user;
    }

    @Override
    public UserInfo queryById(String id) {
        UserInfo user = userMapper.findById(id);
        return user;
    }

    @Override
    public List<Role> queryRoleByUid(String id) {
        return roleMapper.findOtherRolesByUid(id);
    }

    @Override
    // 用户添加角色
    public int addRoles(String userId, String[] roleIds) {
        int sum = 0;
        for (String roleId : roleIds) {
            sum += userMapper.addRole(userId, roleId);
        }
        return sum;
    }

    //添加用户
    @Override
    public void save(UserInfo user) throws Exception {
        UUID uuid = UUID.randomUUID();
        user.setId(uuid.toString().replaceAll("\\-", ""));
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userMapper.save(user);
    }


}
